package cn.iocoder.yudao.module.member.controller.app.weixin;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.member.controller.app.auth.vo.AppAuthLoginRespVO;
import cn.iocoder.yudao.module.member.service.auth.MemberAuthService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Api(tags = "微信小程序")
@RestController
@RequestMapping("/member/wx-miniapp")
@Validated
@Slf4j
public class AppWxAppController {

    @Resource
    private WxMaService maService;

    @Resource
    private MemberAuthService authService;

  /*  @ApiOperation("获取AccessToken")
    @GetMapping("/getAccessToken")
    public CommonResult<String> test() throws WxErrorException {
        return success(this.maService.getAccessToken());
    }
*/
    @ApiOperation("获取登录后的session信息")
    @GetMapping("/jsCode2SessionInfo")
    public CommonResult<WxMaJscode2SessionResult> jsCode2SessionInfo(String code) throws WxErrorException {
        return success(this.maService.jsCode2SessionInfo(code));
    }

    @ApiOperation("微信手机号登录")
    @GetMapping("/login")
    public CommonResult<AppAuthLoginRespVO> login(String sessionKey, String encryptedData, String ivStr) throws WxErrorException {
        WxMaPhoneNumberInfo phoneNoInfo = maService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, ivStr);
        log.info("手机号{}" + phoneNoInfo);
        AppAuthLoginRespVO appAuthLoginRespVO = authService.phoneLogin(phoneNoInfo.getPhoneNumber());
        return success(appAuthLoginRespVO);
    }


}
